/* eslint-disable no-unused-vars */
<template>
  <div class="emergency-manage">
    <div class="header">
      <h2>应急信息管理</h2>
      <el-button type="primary" @click="handleAdd">新增应急信息</el-button>
    </div>
    
    <!-- 表格 -->
    <el-table 
      :data="paginatedData" 
      style="width: 100%" 
      v-loading="loading"
    >
      <el-table-column prop="title" label="标题" width="180"/>
      <el-table-column prop="content" label="内容" show-overflow-tooltip/>
      <el-table-column prop="publishDate" label="发布日期" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.publishDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="expiryDate" label="过期日期" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.expiryDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm
            title="确定要删除这条信息吗？"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="emergencyList.length"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="form.content"
            :rows="4"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="发布日期" prop="publishDate">
          <el-date-picker
            v-model="form.publishDate"
            type="datetime"
            placeholder="选择发布日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="过期日期" prop="expiryDate">
          <el-date-picker
            v-model="form.expiryDate"
            type="datetime"
            placeholder="选择过期日期"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="已发布" value="PUBLISHED"/>
            <el-option label="草稿" value="DRAFT"/>
            <el-option label="已过期" value="EXPIRED"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确 定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import { formatDate } from '@/utils/date'

export default {
  name: 'EmergencyManage',
  data() {
    return {
      loading: false,
      submitting: false,
      emergencyList: [],
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增应急信息',
      form: {
        title: '',
        content: '',
        publishDate: null,
        expiryDate: null,
        status: 'DRAFT'
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        publishDate: [{ required: true, message: '请选择发布日期', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.emergencyList.slice(start, end);
    }
  },
  created() {
    this.fetchEmergencyInfo()
  },
  methods: {
    formatDate,
    async fetchEmergencyInfo() {
      try {
        this.loading = true;
        const response = await request.get('/api/emergency/list');
        // 按创建时间降序排序
        this.emergencyList = response.sort((a, b) => {
          return new Date(b.createdAt) - new Date(a.createdAt);
        });
      } catch (error) {
        console.error('获取应急信息失败:', error);
        this.$message.error('获取应急信息失败');
      } finally {
        this.loading = false;
      }
    },
    handleAdd() {
      this.dialogTitle = '新增应急信息'
      this.form = {
        title: '',
        content: '',
        publishDate: this.formatDateTime(new Date()),
        expiryDate: null,
        status: 'DRAFT'
      }
      this.dialogVisible = true
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields()
      }
    },
    async handleEdit(row) {
      this.dialogTitle = '编辑应急信息'
      this.form = {
        id: row.id,
        title: row.title,
        content: row.content,
        publishDate: row.publishDate,
        expiryDate: row.expiryDate,
        status: row.status,
        createdBy: row.createdBy,
        approvedBy: row.approvedBy
      }
      this.dialogVisible = true
    },
    async handleDelete(id) {
      try {
        await this.$confirm('确认删除这条应急信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await request.delete(`/api/emergency/${id}`);
        this.$message.success('删除成功');
        await this.refreshData(); // 使用新的刷新方法
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      }
    },
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        this.submitting = true
        
        const user = JSON.parse(localStorage.getItem('user'))
        if (!user || !user.id) {
          throw new Error('用户未登录或信息不完整')
        }
        
        const submitData = {
          title: this.form.title,
          content: this.form.content,
          publishDate: this.form.publishDate,
          expiryDate: this.form.expiryDate,
          status: this.form.status,
          createdBy: user.id,
          approvedBy: user.id
        }
        
        console.log('Submit data:', submitData)
        
        let response
        if (this.form.id) {
          response = await request.put(`/api/emergency/${this.form.id}`, submitData)
        } else {
          response = await request.post('/api/emergency', submitData)
        }
        
        this.$message.success(this.form.id ? '更新成功' : '创建成功')
        this.dialogVisible = false
        await this.refreshData() // 使用新的刷新方法
      } catch (error) {
        console.error('Submit error:', error)
        this.$message.error(error.message || '提交失败')
      } finally {
        this.submitting = false
      }
    },
    getStatusType(status) {
      const types = {
        PUBLISHED: 'success',
        DRAFT: 'info',
        EXPIRED: 'danger'
      }
      return types[status] || 'info'
    },
    getStatusText(status) {
      const texts = {
        PUBLISHED: '已发布',
        DRAFT: '草稿',
        EXPIRED: '已过期'
      }
      return texts[status] || status
    },
    handleClose() {
      this.$confirm('确认关闭？未保存的数据将会丢失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogVisible = false
        this.$refs.formRef.resetFields()
      }).catch(() => {})
    },
    formatDateTime(date) {
      if (!date) return null;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      // 如果当前页超出新的总页数，则重置为第一页
      const maxPage = Math.ceil(this.emergencyList.length / this.pageSize);
      if (this.currentPage > maxPage) {
        this.currentPage = 1;
      }
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    // 重写获取数据的方法，添加排序
    async fetchEmergencyInfo() {
      try {
        this.loading = true;
        const response = await request.get('/api/emergency/list');
        // 按创建时间降序排序
        this.emergencyList = response.sort((a, b) => {
          return new Date(b.createdAt) - new Date(a.createdAt);
        });
      } catch (error) {
        console.error('获取应急信息失败:', error);
        this.$message.error('获取应急信息失败');
      } finally {
        this.loading = false;
      }
    },
    // 在新增、编辑、删除成功后重置分页
    async refreshData() {
      await this.fetchEmergencyInfo();
      // 如果当前页超出总页数，重置为第一页
      const maxPage = Math.ceil(this.emergencyList.length / this.pageSize);
      if (this.currentPage > maxPage) {
        this.currentPage = 1;
      }
    }
  }
}
</script>

<style scoped>
.emergency-manage {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
:deep(.el-dialog__body) {
  padding: 20px 30px;
}
:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style> 